<?php

namespace App\Models;

use DB;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;

class InsuranceTemp extends Model
{
	use SoftDeletes;
	protected $fillable = ['shop_id', 'employee_id', 'name', 'type', 'ent', 'ind', 'remarks'];

	public static $typeMap = [
		1	=>	'社保',
		2	=>	'基金',
		3	=>	'商保',
	];

	public function shop()
	{
		return $this->belongsTo(Shop::class);
	}

	public function employee()
	{
		return $this->belongsTo(Employee::class);
	}
    
    public function insuranceFunds()
    {
        return $this->hasMany(InsuranceFund::class);
    }

	public function scopeWhichKeyword($q, $k)
	{
		if (!$k) return $q;
		return $q->where(self::qualifyColumn('name'), 'like', "%{$k}%")
				->orWhere(self::qualifyColumn('remarks'), 'like', "%{$k}%");
	}

	public function scopeWhichEmployee($q, $s, $u = 0)
	{
		if (!$s) return $q;
		if (!is_array($s)) {
			$s = [$s];
		}
		$q->whereIn(self::qualifyColumn('employee_id'), $s);
		if ($u) {
			foreach ($s as $i) {
				DB::table('search_weights')->updateOrInsert(['user_id' => $u, 'employee_id' => $i]);
			}
			DB::table('search_weights')->where('user_id', $u)->whereIn('employee_id', $s)->increment('total');
		}
	}

	public function scopeWhichType($q, $s)
	{
		return $q->when($s, function ($q, $s) {
			if (!is_array($s)) {
				$s = [$s];
			}
			$q->whereIn(self::qualifyColumn('type'), $s);
		});
	}
}
